package com.example.sqlexport.controller;

import com.example.sqlexport.common.Result;
import com.example.sqlexport.entity.DatabaseConfig;
import com.example.sqlexport.entity.SqlExportRequest;
import com.example.sqlexport.service.DatabaseConfigService;
import com.example.sqlexport.service.SqlExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/sql-export")
public class SqlExportController {

    @Autowired
    private SqlExportService sqlExportService;

    @Autowired
    private DatabaseConfigService databaseConfigService;

    @GetMapping("/export/{databaseConfigId}/{tableName}")
    public Result<String> exportSql(
            @PathVariable Long databaseConfigId,
            @PathVariable String tableName,
            @RequestParam(required = false) String whereClause) {
        return Result.success(sqlExportService.exportSql(databaseConfigId, tableName, whereClause));
    }

    @GetMapping("/tables/{databaseConfigId}")
    public Result<List<String>> getTableNames(@PathVariable Long databaseConfigId) {
        DatabaseConfig config = databaseConfigService.findById(databaseConfigId);
        return Result.success(sqlExportService.getTableNames(config));
    }

    @GetMapping("/columns/{databaseConfigId}/{tableName}")
    public Result<List<Map<String, Object>>> getTableColumns(
            @PathVariable Long databaseConfigId,
            @PathVariable String tableName) {
        return Result.success(sqlExportService.getTableColumns(databaseConfigId, tableName));
    }
    
    @PostMapping("/preview")
    public Result<List<Map<String, Object>>> previewData(@RequestBody SqlExportRequest request) {
        return Result.success(sqlExportService.previewData(request));
    }
    
    @GetMapping("/preview")
    public Result<List<Map<String, Object>>> previewDataGet(
            @RequestParam Long databaseConfigId,
            @RequestParam String tableName,
            @RequestParam(required = false) String whereClause,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) Integer limit) {
        
        SqlExportRequest request = new SqlExportRequest();
        request.setDatabaseConfigId(databaseConfigId);
        request.setTableName(tableName);
        request.setWhereClause(whereClause);
        request.setOrderBy(orderBy);
        request.setLimit(limit);
        
        return Result.success(sqlExportService.previewData(request));
    }
} 